package com.test.pudamoney.activity_fragment_pudamoney.base_pudamoney;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.test.pudamoney.R;
import com.test.pudamoney.activity_fragment_pudamoney.loan_pudamoney.LoanMainActivity_pudamoney;
import com.test.pudamoney.bean_pudamoney.config_info_pudamoney.AppShowInfo_pudamoney;
import com.test.pudamoney.bean_pudamoney.process_pudamoney.ProcessInfo_pudamoney;
import com.test.pudamoney.util_pudamoney.PermissionUtil_pudamoney;
import com.test.pudamoney.util_pudamoney.helper_pudamoney.ActivityHelper_pudamoney;
import com.test.pudamoney.util_pudamoney.http_pudamoney.HttpManager_pudamoney;
import com.test.pudamoney.util_pudamoney.http_pudamoney.HttpPresenter_pudamoney;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public abstract class BaseActivity_pudamoney extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private Toast toast_pudamoney;

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {}

    //权限拒绝
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        finish();
    }

    //页面埋点
    public void recordPagePauseEvent_pudamoney() {
        //保存埋点
        String activityName = getClass().getSimpleName();
        if (!TextUtils.isEmpty(activityName)) {
            HttpManager_pudamoney.getInstance().saveUserBuriedPoint((activityName + "_END").toUpperCase());
        }
    }

    //处理用户流程状态
    public void onUserProcessResponse_pudamoney() {
        startActivityForSingleTop_pudamoney(LoanMainActivity_pudamoney.class);
    }

    public void showToastOnUiThread_pudamoney(String text) {
        runOnUiThread(() -> showToast_pudamoney(text));
    }

    @Override
    protected void onResume() {
        super.onResume();
        HttpPresenter_pudamoney.getInstance().setActivity(this);
        recordPageResumeEvent_pudamoney();
    }

    public void showToast_pudamoney(String text) {
        if (toast_pudamoney == null) toast_pudamoney = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        else toast_pudamoney.setText(text);
        toast_pudamoney.show();
    }

    public <T extends BaseActivity_pudamoney> void startActivityForSingleTop_pudamoney(Class<T> activityClass) {
        Intent intent = new Intent(this, activityClass);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity_pudamoney(activityClass);
        finish();
    }

    public void setBackBtn_pudamoney(View btnView) {
        btnView.setOnClickListener(view -> onBackPressed());
    }

    //页面埋点
    public void recordPageResumeEvent_pudamoney() {
        //保存埋点
        String activityName = getClass().getSimpleName();
        if (!TextUtils.isEmpty(activityName)) {
            HttpManager_pudamoney.getInstance().saveUserBuriedPoint((activityName + "_START").toUpperCase());
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (view != null) {
                if (ActivityHelper_pudamoney.canHideKeyboard(view, ev)) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager != null) {
                        ActivityHelper_pudamoney.hideKeyboard(this);
                        EditText editText = (EditText) view;
                        editText.clearFocus();
                    }
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }

    /**
     * 同意所有权限后回调，留给子类实现
     */
    protected void onLaunchPermissionsAllPass_pudamoney() {}

    public <T extends BaseActivity_pudamoney> void startActivity_pudamoney(Class<T> activityClass) {
        startActivity(new Intent(this, activityClass));
    }

    //权限申请通过后执行
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @AfterPermissionGranted(PermissionUtil_pudamoney.REQ_CODE_PERMISSIONS)
    public void onEasyPermissionsAllPass() {
        Log.d(this.getClass().getSimpleName(), "on permissions all pass");
        onLaunchPermissionsAllPass_pudamoney();
    }


    @Override
    protected void onPause() {
        super.onPause();
        HttpPresenter_pudamoney.getInstance().setActivity(null);
        recordPagePauseEvent_pudamoney();
    }

    //检测权限并申请未获取的权限
    public void requestLaunchPermissions_pudamoney(String[] permissions) {
        EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions), PermissionUtil_pudamoney.REQ_CODE_PERMISSIONS, permissions);
    }

    /**
     * 是否需要检查权限，留给子类实现
     * 默认需要检查
     */
    protected boolean onCheckLaunchPermissions_pudamoney() {
        return true;
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        if (AppShowInfo_pudamoney.getInstance().getPermissions().length==0) return;
        if (!PermissionUtil_pudamoney.checkLaunchPermissions(this, AppShowInfo_pudamoney.getInstance().getPermissions()))
            requestLaunchPermissions_pudamoney(AppShowInfo_pudamoney.getInstance().getPermissions());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) requestLaunchPermissions_pudamoney(AppShowInfo_pudamoney.getInstance().getPermissions());
    }
}